<?php

class Bookmark {
  var $conn;
	
  function __construct( $servername, $username, $password, $dbname){
    $this->conn = new mysqli($servername, $username, $password, $dbname);
    if ($this->conn->connect_error){
      $this->conn = -1;
      return;
    }
    $this->conn->set_charset("utf8");
  }

  function __destruct(){
    $this->conn->close();
  }

  function get($uid){
    $result = array();

    $stmtdir = $this->conn->prepare("SELECT id, name, subdir, file FROM bkmk_dir WHERE uid = ? AND parent = ?");
    $stmtfil = $this->conn->prepare("SELECT id, name, link,   time FROM bkmk_fil WHERE uid = ? AND parent = ?");

    $pid = 0;
    $stmtdir->bind_param('ii', $uid, $pid);
    $stmtdir->execute();
    $stmtdir->store_result();
    $stmtdir->bind_result($rootid, $rootname, $rootsubdir, $rootfile);
    if($stmtdir->fetch()){
      $result['id']        = $rootid;
      $result['name']      = $rootname;
      $result['filnum']    = $rootfile;
      $result['subdirnum'] = $rootsubdir;
      $result['fil']       = array();
      $result['subdir']    = array();

      if($rootfile > 0){
        $stmtfil->bind_param('ii', $uid, $rootid);
        $stmtfil->execute();
        $stmtfil->store_result();
        $stmtfil->bind_result($fileid, $filename, $filelink, $roottime);
        while($stmtfil->fetch()){
          array_push($result['fil'], array(
            "id"   => $fileid,
            "name" => $filename,
            "link" => $filelink,
            "time" => $roottime
          ));
        }
      }

      if($rootsubdir > 0){
        $result['subdir'] = $this->loop($uid, $rootid, $stmtdir, $stmtfil);
      }
    }

    $stmtdir->close();
    $stmtfil->close();

    return $result;
  }

  function loop($uid, $pid, $stmtdir, $stmtfil){
    $result = array();

    $stmtdir->bind_param('ii', $uid, $pid);
    $stmtdir->execute();
    $stmtdir->store_result();
    $stmtdir->bind_result($dirid, $dirname, $dirsubdir, $dirfile);
    $dirs = array();
    while($stmtdir->fetch()){
      array_push($dirs, array(
        "id"        => $dirid,
        "name"      => $dirname,
        "filnum"    => $dirfile,
        "subdirnum" => $dirsubdir,
        "fil"       => array(),
        "subdir"    => array()
      ));
    }
    foreach($dirs as $dir){
      
      $did = $dir['id'];

      if($dir['filnum'] > 0){
        $stmtfil->bind_param('ii', $uid, $did);
        $stmtfil->execute();
        $stmtfil->store_result();
        $stmtfil->bind_result($fileid, $filename, $filelink, $roottime);
        while($stmtfil->fetch()){
          array_push($dir['fil'], array(
            "id"   => $fileid,
            "name" => $filename,
            "link" => $filelink,
            "time" => $roottime
          ));
        }  
      }

      if($dir['subdirnum'] > 0){
        $dir['subdir'] = $this->loop($uid, $did, $stmtdir, $stmtfil);
      }

      array_push($result, $dir);

    }

    return $result;
  }
}
?>
